<?php
namespace Admin\Controller;
use Think\Controller;
class IpController extends BaseController{
	public function iplist(){
		$Ip = D('Ip');
		$iplist = $Ip->select();
		$this->assign('iplist', $iplist);
		$this->display();
	}

	public function addIp(){
		$this->display();
	}

	public function allot(){
		$Ip = D('Ip');
		$User = D('User');
		$Iptouser = D('Iptouser');
		$iplist = $Ip->getOpens();
		$userlist = $User->getAdmins();
		$now = $Iptouser->getUsers();
		$this->assign('userlist', $userlist);
		$this->assign('iplist', $iplist);
		$this->assign('now', $now);
		$this->display();
	}

	public function addIpHandle(){	// 添加Ip地址处理器
		$name = I('post.name');
		$title = I('post.title');
		$Ip = D('Ip');
		try{
			$res = $Ip->addIp($name, $title);
			$this->redirect('Admin/Ip/iplist', array(), 0);
		}catch(\Exception $e){
			$this->error($e->getMessage());
		}
	}

	public function allotHandle(){
		$uid = I('post.uid');
		$ips = I('post.ips');
		$Iptouser = D('Iptouser');
		$Iptouser->allot($uid, $ips);
		$this->redirect('Admin/Ip/allot', array(), 0);
	}

	public function setStatus(){
		$id = I('post.id');
		$status = I('post.status')=='true' ? 1 : 0;
		$Ip = D('Ip');
		if($Ip->setOpen($id, $status) !== false){
			$this->ajaxReturn(array('opstatus'=>'success','opparams'=>$_POST));
		}else{
			$this->ajaxReturn(array('opstatus'=>'error'));
		}
	}

	public function updateIp($ip_id=null){		//更新ip。根据有无ip_id判断列表行为
		$ip=D("Ip");
		if($ip_id==null){
			$iplist = $ip->select();
			$this->assign('iplist', $iplist);
			$this->display("Ip/updatelist");
		}
		else{
			$where['id']=$ip_id;
			$res=$ip->where($where)->find();
			if($res===false){
				$this->error("ip信息错误，请重试或联系管理员！",U("Admin/Ip/updateIp"));
			}
			else{
				$this->assign("ipinfo",$res);
				$this->display();
			}
		}
	}

	public function updateIpHandle(){		//更新ip处理
		$ip_id=I("post.ip");//如果需要验证可以使用ip正则匹配
		$ip=D("Ip");
		$data['id']=$ip_id;
		$data['name']=I("post.name");
		$data['title']=I("post.title");
		$res=$ip->save($data);
		if($res===false){
			$this->error("ip不存在，请重试或联系管理员！",U("Admin/Ip/updateIp"));
		}
		else{
			$this->success("修改成功",U("Admin/Ip/updateIp"));
		}
	}

	public function deleteIpHandle($ip_id=null){	//删除ip处理
		if($ip_id==null){
			$this->error('用户信息为空，请重试!',U('Admin/Ip/updateIp'));
		}
		else{
			$ip=D("Ip");
			$where['id']=$ip_id;
			$res=$ip->where($where)->delete();
			if($res===false){
				$this->error('删除失败，请重试！',U('Admin/Ip/updateIp'));
			}
			else{
				$this->success('删除成功！',U('Admin/Ip/updateIp'));
			}
		}
	}
}
